package com.self.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.self.common.constant.CommonConstants;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @version v1.0
 * @ClassName: 新增或修改自动填充公共字段值
 * @Description:
 * @Author: Mac
 * @Date: 2022/5/29 20:07
 */
@Component
public class AutoFiledValueHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId = getUserId();
        //类型一致，填充值不为null，没有改字段
        this.strictInsertFill(metaObject,"lastUpdateTime", Date.class,new Date());
        this.strictInsertFill(metaObject,"createBy", Long.class,userId);
        this.strictInsertFill(metaObject,"created", Date.class,new Date());
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId = getUserId();
        //类型一致，填充值不为null
        this.strictInsertFill(metaObject,"lastUpdateTime", Date.class,new Date());
        this.strictInsertFill(metaObject,"modifyBy", Long.class,userId);
    }

    private Long getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication == null || CommonConstants.ANONYMOUS.equalsIgnoreCase(authentication.getPrincipal().toString())? CommonConstants.ANONYMOUS_ID:Long.valueOf(authentication.getPrincipal().toString());
    }
}
